<template>
	
	<!-- <z-paging>
		
	</z-paging> -->
	
	<view class="main-class">
		<!-- <tn-sticky> -->
			<view class="header-class tn-flex justify-end" >
				<view class="status_bar" style="height: var(--status-bar-height); width: 100%; "></view>			
				<!-- <view class="tn-color-black_text tn-flex justify-between tn-text-xl tn-pl-xl tn-pr-xl tn-pb-xl" >
					<tn-icon name="left-arrow" size="40" @click="back"/>
					<span>购物车详情</span>
					<tn-icon name="title" size="40" />
				</view> -->
				<tn-navbar height="45px" home-icon="" :bottom-shadow = "false" bg-color="tn-type-primary_bg" :before-back="back">确认订单 </tn-navbar>
				
			</view>
			
		<!-- </tn-sticky> -->
		
		<view class="middle-class">
			<view class=" tn-mb-sm">
				<!-- <tn-list-item class="tn-border-bottom tn-gray-disabled_border" :bottom-border="true" > 已选品种 </tn-list-item> -->
				<view class="tn-p-sm tn-shadow tn-flex tn-border-bottom tn-gray-disabled_border">
					<view class="tn-w-3-4 " >
						已选品种
					</view>
					<view class="tn-w-1-4 tn-flex items-center">
						共{{shopClientInfoData.details.filter(item => item.sel === 1).length}}件品种
					</view>
				</view>
				<view class="tn-p-sm tn-shadow tn-flex">
					<view class=" " >
						<tn-button bg-color="tn-gray" shadow shadow-color="tn-gray" class="tn-m-xs" v-for="(item,index) in shopClientInfoData.details.filter(item => item.sel === 1)" :key="index">{{item.goodsname}}</tn-button>
					</view>
				</view>
			</view>
			
			<!-- 银行信息 -->
			<view class="tn-mb-sm">
				<view class="tn-p-sm tn-shadow tn-flex tn-border-bottom tn-gray-disabled_border">
					<view class="tn-w-full">
						银行信息
					</view>
				</view>
				<view class="tn-p-sm tn-shadow">
					<view class="bank-info-item">
						<text class="bank-label">开户银行：</text>
						<text class="bank-value">{{shopClientInfoData.subbranch || '--'}}</text>
					</view>
					<view class="bank-info-item">
						<text class="bank-label">银行账号：</text>
						<text class="bank-value">{{shopClientInfoData.bankaccount || '--'}}</text>
					</view>
					<view class="bank-info-item">
						<text class="bank-label">开户户名：</text>
						<text class="bank-value">{{shopClientInfoData.acctname || '--'}}</text>
					</view>
				</view>
			</view>
			
			<view class=" tn-mb-sm" v-show="billinfo">
				<!-- <tn-list-item class="tn-border-bottom tn-gray-disabled_border" :bottom-border="true" > 支付方式 </tn-list-item> -->
				<view class="tn-p-sm tn-shadow tn-flex tn-border-bottom tn-gray-disabled_border">
					<view class="tn-w-3-4 " >
						单据属性
					</view>
				</view>
				<view class="tn-p-sm tn-shadow tn-flex">
					<tn-switch v-model="isPrePay" active-value="1" inactive-value="0" active-text="预付" inactive-text="非预付" class="switch-class">  </tn-switch>
					&nbsp;&nbsp;&nbsp;&nbsp;
					
			
				</view>
				
			</view>
			
			<view class=" tn-mb-sm input-remark-class">
				<!-- <tn-list-item class="tn-border-bottom tn-gray-disabled_border" :bottom-border="true" > 备注 </tn-list-item> -->
				<view class="tn-p-sm tn-shadow tn-flex tn-border-bottom tn-gray-disabled_border">
					<view class="tn-w-3-4" >
						备注
					</view>
				</view>
				<view class="tn-p-sm tn-shadow">
					<!-- 
					 -->
					<tn-input
					    v-model="remark"
					    type="textarea"
					    placeholder="请输入备注"
						height="180"
						:border = "false"
						confirm-type="done"
						:show-word-limit="true"
						:maxlength="200"
					  />

				</view>
			</view>

			
			
		</view>
		<view class="bottom-buttons">
		  <!-- <tn-button type="success" size="xl" @click="doTurnAround">继续添加</tn-button> -->
		  <view class="tn-flex items-center tn-red_text tn-text-3xl tn-pt-sm">
			  总金额：{{shopClientInfoData.taxamount}}
		  </view>
		  <view class="">
		  	<tn-button type="danger" size="xl" @click="doSaveSettle">提交订单</tn-button>
		  </view>
		</view>
		
	</view>
</template>

<script setup>
	import { ref,reactive,onMounted,watch  } from 'vue'
	import { EventBus } from '@/mitt/EventBus.js';
	import { postCall,postPay  } from '@/api/index.js'
	import { toastMessage } from '@/utils/toast.js'
	import SelectTags from 'tnuiv3p-tn-select-tags/index.vue'
	import { v4 as uuidv4 } from 'uuid';
	import Big from 'big.js';
	
	import { generateUUID } from '@/utils/utils.js'
	
	const procName = "PROC_APP_DO_SHOPPING";
	const shopClientInfoData = reactive({details:[]});
	//{"label":"线上支付","value":"1"}
	const payType = ref([])
	const remark = ref('')
	const payConfig = {};
	let userInfo = {};
	let isAllBill = ref(0);
	let isPreBill = ref(0);
	let isLogistics = ref(0);
	let isLogisticss = ref(0);
	let invoiceType = ref('0');
	let isPrePay = ref(0);
	let uuid = "";
	let doGetPayConfig = async () =>{
		let params = {};
		params["P_PROC_NAME"] = procName;
		params["P_ACTION"] = "PAYCONFIG";		
		await postCall(params).then(res=>{
			if(res){
				if(res.code===200){
					Object.assign(payConfig,res.data.DATASET[0]);
					console.log(payConfig);
				}
			}
			
		})
	}
	onMounted(()=>{
		const tempShopClientInfo = uni.getStorageSync("SHOPCLIENTINFO");
		Object.assign(shopClientInfoData,tempShopClientInfo);
		
		userInfo = uni.getStorageSync('USERINFO');
		// payType.push(userInfo.paytype);
		payType.value = [userInfo.paytype.toString()];
		// console.log(shopClientInfoData.details)
		doGetPayType();
		EventBus.on('shopClientInfo', (objParam) => {
			Object.assign(shopClientInfoData,objParam);
		});
		doGetPayConfig();
		
		getUIInfo();
	})
	
	let back = (val) =>{
		EventBus.emit('shopClientInfo',val);
		// uni.navigateBack();
		return true;
		// uni.setStorageSync("index",2);
		// uni.navigateTo({
		// 	url: '/pages/index/index'
		// });
		// uni.setStorageSync("index",2);
		// EventBus.emit('shopClientInfo',val);
		// return false;
	}
	
	const doTurnAround = ()=>{
		uni.setStorageSync("index",1);
		uni.navigateTo({
			url: '/pages/index/index'
		});
	}
	
	const delShopping=(val,index)=>{
		let params = {};
		params["P_PROC_NAME"] = procName;
		params["P_ACTION"] = "DELETE";
		params["P_ID"] = val.id;
		postCall(params).then(res=>{
			if(res){
				if(res.code===200){
					toastMessage("删除成功！");
					shopClientInfoData.details.splice(index,1);
				}
			}
			
		})
	}
	
	let payTypeData = reactive([]);
	let doGetPayType = async () =>{
		let params = {};
		params["P_PROC_NAME"] = procName;
		params["P_ACTION"] = "PAYTYPE";		
		await postCall(params).then(res=>{
			if(res){
				if(res.code===200){
					Object.assign(payTypeData,res.data.DATASET);
				}
			}
			
		})
	}
	
	
	// let toNavigate = () =>{
	// 	console.log(shopClientInfoData)
	// 	// uni.navigateTo({
	// 	// 	url: '/pages/shop/settle'
	// 	// })
	// 	let params = {};
	// 	params["P_PROC_NAME"] = procName;
	// 	params["P_ACTION"] = "PLAN_SAVE";	
	// 	params["P_ADDRESS"] = shopClientInfoData.address;
	// 	params["P_SUPPLIERSID"] = shopClientInfoData.businessid;
	// 	postCall(params).then(res=>{
	// 		if(res){
	// 			if(res.code===200){
	// 				toastMessage("保存成功！");
	// 				uni.navigateTo({
	// 					url: '/pages/purplan/plan'
	// 				});
	// 			}
	// 		}
			
	// 	})
	// }
	
	let doSaveSettle= async () =>{
		let idList = [];
		for(let j=0;j<shopClientInfoData.details.length;j++){
			if(shopClientInfoData.details[j].sel == "1"){
				idList.push(shopClientInfoData.details[j].id.toString());
			}
		}
		uuid = generateUUID();
		let flag = true;
		const prePay = isPrePay.value
		const receManId = shopClientInfoData.recemanid;
		const addressId = shopClientInfoData.addressid;
		let params = {};
		params["P_PROC_NAME"] = procName;
		params["P_ACTION"] = "PLAN_SAVE";	
		params["P_SUPPLIERSID"] = shopClientInfoData.businessid;
		params["P_ISPREPAY"] = isPrePay.value
		params["P_IDS"] = idList.join(",");
		await postCall(params).then(res=>{
			console.log(res);
			if(res){
				if(res.code===200){
					toastMessage("保存成功！");
					uni.navigateTo({
						url: '/pages/purplan/plan'
					});
				}
			}
		})
		
		
	}
	
	
	let onLineWXPay = (peyTypeValue) =>{
		let params = {};
		params.cusid = payConfig.cusid;
		params.appid = payConfig.appid;
		params.version = payConfig.version;
		params.trxamt =  parseFloat(new Big(shopClientInfoData.taxamount).times(100)).toString(); //;
		params.reqsn = uuid;
		params.notify_url = payConfig.notifyurl;
		params.body = shopClientInfoData.businessname;
		params.remark = userInfo.staffid;
		if(peyTypeValue == 1){
			params.paytype = "W06";
		}else if(peyTypeValue == 2){
			params.paytype = "A02";
		}
		
		params.randomstr = uuid;
		params.signtype = payConfig.signtype;
		postPay(params).then(res=>{
			console.log(res);
			if(res){
				if(res.code===200){
					params.sign = res.data;
					var queryParams = [];
					for (var key in params) {
					  if (params.hasOwnProperty(key)) {
					    // var value = encodeURIComponent(params[key]);
						var value = params[key];
					    queryParams.push(key + "=" + value);
					  }
					}
					if(peyTypeValue==1){
						plus.share.getServices(res=>{
							let sweixin = '';
							for (var i = 0; i < res.length; i++) {
								let t = res[i];
								if (t.id == 'weixin') {
								  sweixin = t;
								}
							}
							console.log(sweixin)
							if(sweixin){
								sweixin.launchMiniProgram(
									{
										id: 'gh_e64a1a89a0ad',  // 要跳转小程序的原始ID
										path: 'pages/orderDetail/orderDetail'+"?"+queryParams.join("&"),  //  可带参数
										type: 0   // 微信小程序版本类型可取值： 0-正式版； 1-测试版； 2-体验版。 默认值为0。
									},
									// 目标小程序点击返回App后执行的回调，在此接收微信小程序传递的参数
									res2 => {
										console.log(typeof res2, res2)
										// res2是微信小程序传递回来的参数 类型为string 需转化为js对象使用
										let result = JSON.parse(res2)
										console.log(result) 
										// 拿到参数后执行你需要的逻辑    
										// ......   
									},
									  err2 => {
										console.log(err2)
									  }
									);
							}
						})
					} 
					if(peyTypeValue==2){
						
						let alipayUrl = null;
						 
						 if (uni.getSystemInfoSync().platform == "ios") {
							alipayUrl = 'alipay://platformapi/startapp?appId=2021001104615521';
						 }else{
							alipayUrl = 'alipays://platformapi/startapp?appId=2021001104615521';
						 }
						
						//alipayUrl 已经有? 问号了，所以这里需要进行编码
						// let params = encodeURIComponent('?'+queryParams.join("&"))
						 const query = encodeURIComponent("payinfo=" + encodeURIComponent(JSON.stringify(params)));
						
						// page=pages/index/index  跳转到支付宝小程序页面的页面路径
						alipayUrl  = `${alipayUrl}&page=pages/orderDetail/orderDetail&thirdPartSchema=&query=${query}`
						//唤起支付宝
						plus.runtime.openURL(alipayUrl);
						// window.location.href = alipayUrl;

					   console.log('跳转到支付宝小程序')
					   // uni.navigateToAlipayMiniProgram({
					   //   appId: '2021001104615521',
					   //   path: `pages/orderDetail/orderDetail&thirdPartSchema=&query=${query}`, // 要打开的小程序页面路径
					   //   success: function() {
					   //     console.log('跳转到支付宝小程序成功');
					   //   },
					   //   fail: function(error) {
					   //     console.error('跳转到支付宝小程序失败', error);
					   //   }
					   // });

					}
				}else{
					toastMessage(res.msg);
				}
			}
			
		})
	}
	
	let dhinfo = ref(true);
	let billinfo = ref(true);
	
	const getUIInfo =()=>{
		let params = {};
		params["P_PROC_NAME"] = procName;
		params["P_ACTION"] = "UI";
		postCall(params).then(res=>{
			if(res){
				if(res.code===200){
					if(res.data.DATASET.length>0){
						dhinfo.value = (res.data.DATASET[0].dhinfo === 'TRUE');
						billinfo.value = (res.data.DATASET[0].billinfo === 'TRUE');
						
						console.log(dhinfo.value);
						console.log(billinfo.value);
						
					}
				}
			}
			
		})
	}
	
	let doGetAddress = () =>{
		uni.navigateTo({
			url: '/pages/shop/address'
		});
	}
	
	let doGetDHAddress = () =>{
		uni.navigateTo({
			url: '/pages/shop/dhaddress'
		});
	}
	
</script>

<style scoped>
.header-class{
	height: 17vh !important;
	flex-direction: column;
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	color: #fff;
	padding: 10px 0;
	text-align: center;
	z-index: 999	
}
.image-class{
	width: 100%;
	height: 100%;
}
.card-class{
	position: relative;
}

.bottom-buttons {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
	background-color: #fff; /* 设置底部背景色 */
	padding: 10px; /* 设置内边距 */
	display: flex;
	justify-content: space-between;
	box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1); /* 设置底部阴影 */
	padding-bottom: calc(env(safe-area-inset-bottom) + 20px);
	height: 8vh;
}

.middle-class{
	margin-top: 17vh;
	width: 95vw;
	margin-left: 2.5vw;
}
.scroll-view-class{
	padding-bottom: 8.5vh;
}
.tag-class{
	background-color: #E1D9D7;
	width: 100%;
}
.switch-class{
	color: #000;
}
.input-remark-class{
	margin-bottom: 9vh;
}

.bank-info-item {
	display: flex;
	align-items: center;
	padding: 12rpx 0;
}

.bank-label {
	font-size: 28rpx;
	color: #666;
	width: 160rpx;
	flex-shrink: 0;
}

.bank-value {
	font-size: 28rpx;
	color: #333;
	flex: 1;
}
</style>
